    // templates/deliver/pages/bindingorder/bindingorder.js
  
    import Dialog from '@vant/weapp/dialog/dialog';
    import Toast from '@vant/weapp/toast/toast';
    import Notify from '@vant/weapp/notify/notify';
    import {clearUserLocalStorage} from "../../../../utils/util";
    import {authorization} from "../../../../utils/location";
    const app = getApp();
    Page({

        /**
         * 页面的初始数据
         */
        data: {
            orderAll: [], //数据
            markers: [],
            image: '/templates/deliver/img/business.png', //地图图标
            longitude: 0, //经纬度
            latitude: 0,
            scale: 11,
            id: 0, //司机id
            username: '', //司机姓名
            show: true, //控制加载动画
            activeNames: ['0'], //点击折叠
            ball: false, //控制弹出层
            fileList: [], //图片集合
            imgCount: 3, //设置上传图片数量
            controlUpload: true, //控制文件上传
            imgDelete: true, //控制文件删除
            buttstatus: 1, //点击提交按钮禁用
            imgMax: 1048576 * 2, //单图片大小
            order_id: 0,
            values: '',
            ordername: '', //收货人
            status: false, //状态是不是有数据
            result: [], //控制获取的数据
            checkedAll: false, //控制全选  
            dshow: true, // 控制送达栏目,

            view_delivery_man_id: 0,
            view_driver_name: '',
            view_delivery_district_id: 0

        },
        /**
         * 点击全选
         */
        onResult(event) {
            this.setData({
                result: event.detail
            })
            //注意获取顺序
            let orderAll = this.data.orderAll
            let result = this.data.result
            if (orderAll.length !== result.length) {
                this.setData({
                    checkedAll: false,
                })
            } else {
                this.setData({
                    checkedAll: true,
                })
            }
           
        },
        allChecked(event) {
            let orderAll = this.data.orderAll
            let results = []
            for (let i = 0; i < orderAll.length; i++) {
                results.push(String(orderAll[i]['id']))
            }
            this.setData({
                result: results,
                checkedAll: event.detail,
                
            })
            if (this.data.checkedAll === false) {
                this.setData({
                    result: [],
                })
            }
            //console.log(this.data.result)
        },
        /**
         * 点击打开
         */
        onChange(event) {
            this.setData({
                activeNames: event.detail,
            });
        },
        /**
         * 生命周期函数--监听页面加载
         */
        onLoad(options) {
            let that = this
            var delivery_man = wx.getStorageSync('delivery_man');

            let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id')
            let view_driver_name = ''
            let view_delivery_district_id = 0
            if (view_delivery_man_id > 0) {
                view_driver_name = wx.getStorageSync('view_driver_name')
                view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
            }

            this.setData({
                id: delivery_man.delivery_man_id, //司机id
                username: delivery_man.delivery_man_name, //司机姓名
                view_delivery_man_id,
                view_driver_name,
                view_delivery_district_id
            })
            //获取当前定位
            wx.getLocation({
                type: "gcj02",
                success: res => {
                    let xian_latitude = 34.26986287676798
                    let xian_longitude =108.9471324706426

                    let map_latitude = xian_latitude
                    let map_longitude = xian_longitude
                    if (that.getDistance(xian_latitude, xian_longitude, res.latitude, res.longitude) < 300) {
                        map_latitude = res.latitude
                        map_longitude = res.longitude
                    }

                    that.setData({
                        latitude: map_latitude,
                        longitude: map_longitude,
                    })
                }
            })
            this.driverOrderAll()
            //接收上级传递的参数
            // const eventChannal = this.getOpenerEventChannel();
            // eventChannal.on('orderAll', function (res) {
            //     let orderAll = JSON.parse(res)
            //     that.setData({
            //         orderAll
            //     })
            //     console.log(orderAll)
            // })

        },

        on_marker_or_label_tap(e) {
            let tap = e.detail
            let marker_id = null
            if (tap) {
                marker_id = tap.markerId
                this.getViewOrderInfo(marker_id)
            }
            /*

            // 使用find方法在markers数组中查找id等于marker_id的marker
            let tapMarker = this.data.markers.find(marker => marker.id === marker_id);

            // 检查是否找到了marker并处理结果
            if (tapMarker) {
                console.log("找到了marker:", tapMarker);
                this.setData({
                    show_actions: true,
                    tapMarker: tapMarker
                })
            } else {
                Toast('没有有效的数据')
            }
            */

        },
        /**
         * 确认送达/并且更新司机位置--------
         */
        delivery(e) {
            let name = e.currentTarget.dataset.name //获取传递的id参数
            let _this = this
            let id = e.currentTarget.dataset.id //获取传递的id参数
            let url = app.globalData.URL
            let mall_id = app.globalData.mall_id
            Dialog.confirm({
                    title: '确认送达',
                    message: '确定' + name + '的订单已经送达',
                })
                .then(() => {
                    wx.request({
                        url: url + '/deliver.OrderV2/affirmOrder',
                        method: 'GET',
                        data: {
                            order_id: id,
                            mall_id
                        },
                        success(res) {
                            //console.log(res)
                            if (res.data.code === 0) {
                                Notify({
                                    type: 'success',
                                    message: '送达成功'
                                });
                                _this.driverOrderAll();

                            } else {
                                Notify({
                                    type: 'danger',
                                    message: '送达失败'
                                });
                            }
                        }
                    })
                })
                .catch(() => {
                    // on cancel
                    Notify({
                        type: 'warning',
                        message: '取消送达'
                    });
                });


        },
        /**
         * 订单导航
         */
        ontravel(e) {
            // console.log(e)
            let name = e.currentTarget.dataset.name // 获取用户信息
            let address = e.currentTarget.dataset.address //获取配送地址
            let latitude = e.currentTarget.dataset.latitude //获取经纬度
            let longitude = e.currentTarget.dataset.longitude
            wx.openLocation({
                name: name,
                address: address,
                latitude: Number(latitude),
                longitude: Number(longitude),
            })
        },
        /**
         * 订单解绑
         */
        onUnbind(e) {
            let name = e.currentTarget.dataset.name
            let that = this
            let url = app.globalData.URL
            let mall_id = app.globalData.mall_id //获取主商城id
            let id = e.currentTarget.dataset.id
            Dialog.confirm({
                    title: '解绑',
                    message: '确定要解绑' + name + '订单？',
                })
                .then(() => {
                    // on confirm
                    wx.request({
                        url: url + '/deliver.OrderV2/delDeliverOrder',
                        method: "DELETE",
                        data: {
                            mall_id,
                            id
                        },
                        success(res) {
                            //console.log(res)
                            if (res.data.code === 0) {
                                Toast('解绑成功~')
                                that.onClose()
                                that.driverOrderAll()
                            } else {
                                Toast('解绑失败~')
                            }
                        }
                    })
                })
                .catch(() => {
                    // on cancel
                    Toast('解绑失败~')
                });


        },
        /**
         * 送达信息提交
         */
        dataSubmit(e) {
            let that = this
            let url = app.globalData.URL
            let mall_id = app.globalData.mall_id //获取主商城id
            let fileList = this.data.fileList //获取上传图片集合
            let id = e.detail.value.id //获取id
            let remark = e.detail.value.remark //获取备注信息
            let status = e.detail.target.id //获取按钮id
            // console.log(fileList, id, remark, status)
            wx.request({
                url: url + '/deliver.OrderV2/orderRemark',
                data: {
                    mall_id,
                    fileList,
                    id,
                    remark,
                    status
                },
                method: "POST",
                success: res => {
                    // console.log(res)
                    if (res.data.code === 0) {
                        Toast('提交成功~')
                        that.onClose()
                        that.driverOrderAll()
                    } else {
                        Toast('提交失败~')
                    }
                }
            })
        },

        call_mobile(e) {
            let mobile = e.currentTarget.dataset.mobile
            console.log(mobile)
            wx.makePhoneCall({
                phoneNumber: mobile,
                success: function () {
                    console.log("拨打电话成功！")
                },
                fail: function () {
                    console.log("拨打电话失败！")
                }
            })
        },
        /**
         * 根据id 查询订单
         */

        queryOrder(e) {
            let id = e.currentTarget.dataset.id
            this.getViewOrderInfo(id)
        },

        getViewOrderInfo(marker_id) {
            let id = marker_id
            let url = app.globalData.URL
            let mall_id = app.globalData.mall_id //获取主商城id
            wx.request({
                url: url + '/deliver.OrderV2/getViewOrderInfo',
                method: "GET",
                data: {
                    id,
                    mall_id
                },
                success(res) {
                    // console.log(res)
                    if (res.data.code === 0) {
                        let dataStr = JSON.stringify(res.data.data)
                        wx.navigateTo({
                            url: '/templates/deliver/pages/orderAll/orderAll',
                            success(res) {
                                res.eventChannel.emit('orderAll', dataStr)
                            }
                        })
                    }
                }
            })
        },
        /**
         * 弹出层控制
         */
        ballPopup(e) {
            let id = e.currentTarget.dataset.id //获取传递的id参数
            let ordername = e.currentTarget.dataset.ordername
            this.setData({
                ball: true,
                order_id: id,
                ordername,
                dshow: false,
                result: [],
                checkedAll: false
            }) //打开弹窗
        },

        /**
         * 关闭弹出层控制
         */
        onClose() {
            this.setData({
                fileList: [],
                values: '',
                ball: false,
                dshow: true,
            })
        },
        /* 上传文件查看图片大小 */
        imgSize(event) {
            let imgMax = this.data.imgMax; //获取默认上传文件大小
            const {
                file
            } = event.detail; //获取上传文件数组
            for (let i = 0; i < file.length; i++) {
                if (file[i].size > imgMax) {
                    Toast('大小超过2MB~')
                }
            }
        },
        /* 上传文件后事件，处理照片放入OSS回显 */
        afterRead(event) {
            // console.log('上传触发1')
            let that = this
            const {
                file
            } = event.detail; //获取上传文件数组
            for (let i = 0; i < file.length; i++) {
                /* 开始上传 */
                wx.uploadFile({
                    url: app.globalData.URL + '/deliver.Upload/uploadImg',
                    filePath: file[i]['url'], //传递文件
                    name: 'image', //获取照片信息的名称
                    success(res) {
                        // console.log('上传触发2')
                        let result = JSON.parse(res.data) //传过来的是json 需要转换成对象
                        Toast('上传成功~~')
                        const {
                            fileList = []
                        } = that.data;
                        fileList.push({
                            url: result.data
                        })
                        that.setData({
                            fileList
                        });
                    }
                })
            }
        },
        /**
         * 删除上传的照片
         */
        imgDelete(event) {
            let that = this;
            let urlPath = event.detail.file.url
            wx.request({
                url: app.globalData.URL + '/deliver.Upload/deleteImg',
                method: 'DELETE',
                header: {

                },
                data: {
                    path: urlPath
                },
                success: res => {
                    // console.log(res)
                    if (res.data.code === 1) {
                        Toast('删除图片失败');
                    } else {
                        const {
                            fileList = []
                        } = that.data;
                        fileList.splice(event.detail.index, 1)
                        that.setData({
                            fileList
                        });
                        Toast('删除成功');
                    }
                }
            })
        },
        /**
         * 生命周期函数--监听页面初次渲染完成
         */
        onReady() {

        },

        /**
         * 生命周期函数--监听页面显示
         */
        onShow() {

        },

        /**
         * 生命周期函数--监听页面隐藏
         */
        onHide() {

        },

        /**
         * 生命周期函数--监听页面卸载
         */
        onUnload() {

        },

        /**
         * 页面相关事件处理函数--监听用户下拉动作
         */
        onPullDownRefresh() {
            let that = this
            setTimeout(function () {
                that.driverOrderAll();
            }, 2000);
            wx.stopPullDownRefresh()
        },

        /**
         * 页面上拉触底事件的处理函数
         */
        onReachBottom() {

        },

        /**
         * 用户点击右上角分享
         */
        onShareAppMessage() {

        },
        tap_avatar(e) {
            console.log(e)
            wx.pageScrollTo({
                scrollTop: 0,
                duration: 300
            })
            let latitude = e.currentTarget.dataset.latitude //获取传递的id参数
            let longitude = e.currentTarget.dataset.longitude //获取传递的id参数
            this.setData({
                'scale': 17,
            })
            this.map = wx.createMapContext('locationM', this)
            this.map.moveToLocation({
                longitude: Number(longitude),
                latitude: Number(latitude),
                success: function () {

                }
            })
        },

        /**
         * 根据司机id和姓名获取未送达订单信息
         */
        async driverOrderAll() {
            let _this = this
            let id = this.data.id
            let username = this.data.username
            let mall_id = app.globalData.mall_id
            let markers = []


            let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
            let view_driver_name = ''
            let view_delivery_district_id = 0
            if (view_delivery_man_id > 0) {
                view_driver_name = wx.getStorageSync('view_driver_name')
                view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
            }

            const {
                data: res
            } = await wx.p.request({
                url: app.globalData.URL + '/deliver.OrderV2/queryBinDing',
                method: "GET",
                data: {
                    id,
                    username,
                    mall_id,
                    view_delivery_district_id,
                    view_delivery_man_id,
                    view_driver_name
                },
            })
            let response = res.data
            let orderAll = response.orders
            let area_list = response
            let max_distance = response.max_distance
            console.log(orderAll[0])
            if (orderAll) {
                //根据距离重组数据排序
                for (let i = 0; i < orderAll.length; i++) {
                    //新组地图定位
                    markers[i] = ({
                        iconPath: "../../img/icon-hc.png",
                        id: orderAll[i].id,
                        latitude: parseFloat(orderAll[i].latitude),
                        longitude: parseFloat(orderAll[i].longitude),
                        width: 23,
                        height: 23,
                        nearbyCount: 0,
                        nearMarkers: [],
                        nearMarkersInfo:[],
                        callout: {
                            content: orderAll[i].order_name + '' + (i+1),
                            store_name: orderAll[i].order_name,
                            fontSize: 14,
                            padding: true,
                            color: '#ffffff',
                            display: 'ALWAYS',
                            textAlign: 'center',
                            borderRadius: 10,
                            bgColor: '#0077ffbe'
                        },
                    })
                    //数组换算距离
                    orderAll[i]['resKm'] = this.getDistance(_this.data.latitude, _this.data.longitude, parseFloat(orderAll[i].latitude), parseFloat(orderAll[i].longitude))
                }

                // 计算每两个定位点之间的距离
                for (let i = 0; i < markers.length; i++) {
                    for (let j = i + 1; j < markers.length; j++) {
                        let distance = this.calculateDistance(markers[i].latitude, markers[i].longitude, markers[j].latitude, markers[j].longitude);
                        if (distance <= max_distance) {
                            markers[i].nearbyCount += 1;
                            markers[j].nearbyCount += 1;

                            markers[i].nearMarkers.push(markers[j].id);
                            markers[j].nearMarkers.push(markers[i].id);

                            markers[i].nearMarkers.push(markers[j].id);
                            markers[j].nearMarkers.push(markers[i].id);

                            markers[i].nearMarkersInfo.push({distance: max_distance - distance, })

                        }
                    }
                }

                markers.forEach(marker => {
                    marker.callout.content += ` (${marker.nearbyCount})`;
                });

                //根据距离排序
                orderAll = _this.sortArr(orderAll);
                this.setData({
                    show: false,
                    orderAll,
                    markers
                })

                console.log('markers:', markers)
                Notify({
                    type: 'success',
                    message: '加载完成~~'
                });
            } else {
                Toast.fail('没有数据~');
                this.setData({
                    status: true,
                    markers: [],
                    orderAll: [],
                    show: false,
                })
            }
        },
        //根据距离计算远近
        sortArr(newArray) {
            var arr = newArray;
            var s = "";
            for (var i = 1; i < arr.length; i++) {
                for (var j = i; j > 0; j--) {
                    if (arr[j].resKm > arr[j - 1].resKm) {
                        s = arr[j];
                        arr[j] = arr[j - 1];
                        arr[j - 1] = s;
                    }
                }
            }
            return newArray.reverse();

        },
        // 经纬度计算距离
        getDistance(lat1, lng1, lat2, lng2) {

            var radLat1 = lat1 * Math.PI / 180.0;
            var radLat2 = lat2 * Math.PI / 180.0;
            var a = radLat1 - radLat2;
            var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378.137; // EARTH_RADIUS;
            s = Math.round(s * 10000) / 10000;
            s = s.toFixed(2);
            return parseFloat(s);
        },
        calculateDistance(lat1, lon1, lat2, lon2) {
            function toRad(x) {
                return x * Math.PI / 180;
            }

            let R = 6371; // 地球半径（公里）
            let dLat = toRad(lat2 - lat1);
            let dLon = toRad(lon2 - lon1);
            let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2);
            let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            let distance = R * c;
            return distance * 1000; // 转换为米
        },

        /**
         * 点击全选 订单全部送达
         */
        onClickUpdate(event) {
            let that = this
            //弹窗提醒
            Dialog.confirm({
                title: '确认送达？',
                message: '是否确定？全部送达？',
              })
                .then(() => {
                  // on 确定提交
                    let resultAll = this.data.result
                    let arr = []
                    let url = app.globalData.URL
                    let mall_id = app.globalData.mall_id
                    for(let i=0 ; i< resultAll.length; i++){
                        arr.push(Number(resultAll[i]))
                    }
                  wx.request({
                    url: url + '/deliver.OrderV2/getIdAllUpdate',
                    method: "POST",
                    dataType: "json",
                    header:{ },
                    data: {
                        mall_id,
                        arr
                    },
                    success: res=>{
                        console.log(res)
                        if(res.data.code === 0 ){
                            Toast('送达成功');
                            that.setData({
                                result: []
                            })
                            that.driverOrderAll()
                        }else{
                            Toast('送达失败');
                        }
                    },
                    fail(s){
                        //调用失败
                        Toast('系统异常');
                    },
                    complete(r){
                        //成功失败都调用
                    }
                  })
                })
                .catch(() => {
                  // on 取消
                  Notify({ type: 'warning', message: '取消送达' });
                });
        }



    })